<?php
/**
* File that contains AuthController class.
* @package busmap
*/

/**
* AuthController class is responsible for user login.
* @package busmap
*/
class AuthController extends Zend_Controller_Action
{
	/**
	* Initialize function does nothing.
	*/
    public function init()
    {
        /* Initialize action controller here */
    }

	/**
	* Index does also nothing.
	*/
    public function indexAction(){
			
    }

	/**
	* Function for logging out. Clears session variables.
	*/
	public function logoutAction(){

		$ns = new Zend_Session_Namespace('Auth');
		$ns->id = 0;
		$ns->level = 0;
		$ns->username = '';

	}

	/**
	* Function for logging in.
	* Checks inserted username and password from database and sets session variables.
	*/
	public function loginAction(){

		$db = $this->_getParam('db');

		$loginForm = new Application_Form_Auth_Login();

		if (count($_POST) && $loginForm->isValid($_POST)) {

			$adapter = new Zend_Auth_Adapter_DbTable(
				$db,
				'users',
				'username',
				'password',
				'MD5(?)'
				);

			$adapter->setIdentity($loginForm->getValue('username'));
			$adapter->setCredential($loginForm->getValue('password'));

			$auth   = Zend_Auth::getInstance();
			$result = $auth->authenticate($adapter);

			if ($result->isValid()) {
				
				$authNamespace = new Zend_Session_Namespace('Auth');
				$authNamespace->user = $adapter->getResultRowObject()->username;
				$authNamespace->id = $adapter->getResultRowObject()->id;
				$authNamespace->level = $adapter->getResultRowObject()->level;

				$this->_redirect('/admin');
				return;
			}else{
				$loginForm->addError('Vale kasutajanimi või parool');
			}

		}

		$this->view->loginForm = $loginForm;
     
	}

}
